package org.example.chat.server;

import org.example.chat.common.Message;
import org.example.chat.common.MessageType;

import java.io.*;
import java.net.Socket;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author : hmxchen
 * @program : modules-api
 * @description :
 * @create : 2022-04-26 12:01
 **/
public class ServerThreadConnectClient implements Runnable{

    private Socket socket;
    private String userId;

    public ServerThreadConnectClient() {
    }

    public ServerThreadConnectClient(Socket socket, String userId) {
        this.socket = socket;
        this.userId = userId;
    }

    public Socket getSocket() {
        return socket;
    }

    ManageServerThreadConnectClient manageServerThreadConnectClient = new ManageServerThreadConnectClient(userId,this);

    @Override
    public void run() {
        while (true){
//            synchronized (this) {
            try {
                //登陆成功后，就把登陆的用户放到用户列表里
                manageServerThreadConnectClient.addServerThreadConnectClient(userId,this);
                //客户端要做什么事情都要给服务器发消息，需得到服务器的回应
                //客户端自从登录验证让服务器帮了忙，登录后所有的事情都要麻烦服务器做中转站，接收-存储-传达
                //System.out.println("线程报告： "+userId+" 已登录");
                InputStream inputStream = socket.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(inputStream);
                //客户端除了登录验证是用的User类型包裹，其他都是Message类型发送
                Message message = (Message) ois.readObject();
                String msgType = message.getMsgType();
                String senderId = message.getSender();
                //根据客户端发送过来的消息类型，再按事情类型分别帮客户端解决
                if (msgType.equals(MessageType.ONLINE_USERS.getCode())){
                    //客户端想获取所有在线用户列表
                    String allUserIds = manageServerThreadConnectClient.getAllUserIds();
                    //服务器将查出来的用户id集合放到消息里发出去
                    Message onlineUsersMessage = new Message();
                    onlineUsersMessage.setSender(message.getSender());
                    onlineUsersMessage.setContent(allUserIds);
                    onlineUsersMessage.setMsgType(MessageType.ONLINE_USERS.getCode());
                    //服务器将打包好的消息发送给客户端
                    //ServerThreadConnectClient serverThread = manageServerThreadConnectClient.queryServerThreadConnectClient(senderId);
                    //OutputStream outputStream = serverThread.getSocket().getOutputStream();
                    OutputStream outputStream = socket.getOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(outputStream);
                    oos.writeObject(onlineUsersMessage);
                }else if (msgType.equals(MessageType.PUBLIC_CHAT.getCode())){
                    Message publicChatMsg = new Message();
                    publicChatMsg.setContent(message.getContent());
                    publicChatMsg.setSender(senderId);
                    publicChatMsg.setMsgType(MessageType.PUBLIC_CHAT.getCode());

                    Map<String, ServerThreadConnectClient> all = manageServerThreadConnectClient.getAll();
                    //发消息的本人服务器就不要再通知啦
                    Iterator<String> iterator = all.keySet().iterator();
                    while (iterator.hasNext()){
                        String userId = iterator.next();
                        if (!userId.equals(senderId)){
                            ServerThreadConnectClient thread = manageServerThreadConnectClient.queryServerThreadConnectClient(userId);
                            ObjectOutputStream ooss = new ObjectOutputStream(thread.getSocket().getOutputStream());
                            ooss.writeObject(publicChatMsg);
                        }
                    }
                    System.out.println("村民们，服务器转发客户端发送文件的消息已广播啦");
                }else if (msgType.equals(MessageType.PRIVATE_CHAT.getCode())){
                    Message primsg = new Message();
                    primsg.setSender(message.getSender());
                    primsg.setReceiver(message.getReceiver());
                    primsg.setContent(message.getContent());
                    primsg.setMsgType(MessageType.PRIVATE_CHAT.getCode());
                    //给指定用户发送消息
                    ServerThreadConnectClient receiverThread = manageServerThreadConnectClient.queryServerThreadConnectClient(message.getReceiver());
                    ObjectOutputStream oos = new ObjectOutputStream(receiverThread.getSocket().getOutputStream());
                    oos.writeObject(primsg);
                }else if (msgType.equals(MessageType.SEND_FILE.getCode())){
                    //获取接收人线程
                    ServerThreadConnectClient receiverThread = manageServerThreadConnectClient.queryServerThreadConnectClient(message.getReceiver());
                    ObjectOutputStream oos = new ObjectOutputStream(receiverThread.getSocket().getOutputStream());
                    oos.writeObject(message);
                    System.out.println(message.getReceiver()+": 注意啦，"+message.getSender()+"： 给你发邮件了");
                }else if (msgType.equals(MessageType.EXIT_SYSTEM.getCode())){
                    List<ServerThreadConnectClient> allUsers = manageServerThreadConnectClient.getAllUsers();
                    for (ServerThreadConnectClient userId : allUsers) {
                        ObjectOutputStream oos = new ObjectOutputStream(userId.getSocket().getOutputStream());
                        oos.writeObject(message);
                    }
                }else {
                    System.out.println("other msgtype");
                }

            } catch (Exception e) {
                e.printStackTrace();
                try {
                    socket.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}
//}
